package collection;

import java.util.Iterator;

public class MergedIterator<E> implements Iterator<E>{
	
	Iterator<Iterator<E>> iterIterator;
	Iterator<E> curIter;
	E next;
	
	public MergedIterator(SLinkedList<Iterator<E>> iterList)
	{
		this.iterIterator = iterList.elementsIterator();
		setCurIter();
		setNext();
	}

	private void setCurIter() 
	{
		if (this.iterIterator.hasNext())
		{
			this.curIter = this.iterIterator.next();
		}
	}
	
	private void setNext()
	{
		if (this.curIter == null)
		{
			return ;
		}
		else if (this.curIter.hasNext())
		{
			this.next = this.curIter.next();
		}
		else if(this.iterIterator.hasNext())
		{
			setCurIter();
			setNext();
		}
	}
	
	@Override
	public boolean hasNext() 
	{
		return this.next != null;
	}

	@Override
	public E next() 
	{
		E retVal = this.next;
		this.next = findNext();
		
		return retVal;
	}

	private E findNext() 
	{
		if (this.curIter == null)
		{
			return null;
		}
		else if (this.curIter.hasNext())
		{
			return this.curIter.next();
		}
		else if (this.iterIterator.hasNext())
		{
			this.curIter = this.iterIterator.next();
			return findNext();
		}
		
		this.curIter = null;
		
		return null;
	}

	@Override
	public void remove() 
	{
		throw new UnsupportedOperationException();
	}

}
